"""
管理后台 - 产品管理接口
"""
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession

from app.dependencies import get_db, get_current_user
from app.schemas.common import ResponseModel, PaginatedResponse
from app.schemas.content import ProductCreate, ProductUpdate, ProductResponse
from app.crud.base import CRUDBase
from app.models.content import Product


router = APIRouter()
crud_product = CRUDBase[Product, ProductCreate, ProductUpdate](Product)


@router.get("", response_model=ResponseModel)
async def get_products(
    page: int = Query(1, ge=1),
    page_size: int = Query(10, ge=1, le=100),
    category_id: Optional[int] = Query(None),
    status: Optional[int] = Query(None),
    db: AsyncSession = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """
    获取产品列表
    """
    filters = {}
    if category_id is not None:
        filters["category_id"] = category_id
    if status is not None:
        filters["status"] = status
    
    skip = (page - 1) * page_size
    products = await crud_product.get_multi(db, skip=skip, limit=page_size, filters=filters)
    total = await crud_product.get_count(db, filters=filters)
    
    return ResponseModel(
        data=PaginatedResponse(
            total=total,
            page=page,
            page_size=page_size,
            items=[ProductResponse.model_validate(p) for p in products]
        )
    )


@router.get("/{product_id}", response_model=ResponseModel)
async def get_product(
    product_id: int,
    db: AsyncSession = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """
    获取产品详情
    """
    product = await crud_product.get_by_id(db, id=product_id)
    if not product:
        raise HTTPException(status_code=404, detail="产品不存在")
    
    return ResponseModel(data=ProductResponse.model_validate(product))


@router.post("", response_model=ResponseModel)
async def create_product(
    product_in: ProductCreate,
    db: AsyncSession = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """
    创建产品
    """
    product = await crud_product.create(db, obj_in=product_in)
    return ResponseModel(
        code=201,
        message="创建成功",
        data=ProductResponse.model_validate(product)
    )


@router.put("/{product_id}", response_model=ResponseModel)
async def update_product(
    product_id: int,
    product_in: ProductUpdate,
    db: AsyncSession = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """
    更新产品
    """
    product = await crud_product.get_by_id(db, id=product_id)
    if not product:
        raise HTTPException(status_code=404, detail="产品不存在")
    
    product = await crud_product.update(db, db_obj=product, obj_in=product_in)
    return ResponseModel(
        message="更新成功",
        data=ProductResponse.model_validate(product)
    )


@router.delete("/{product_id}", response_model=ResponseModel)
async def delete_product(
    product_id: int,
    db: AsyncSession = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """
    删除产品
    """
    success = await crud_product.delete(db, id=product_id)
    if not success:
        raise HTTPException(status_code=404, detail="产品不存在")
    
    return ResponseModel(message="删除成功")

